import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response, user):
    # 合并购物车
    # 1. 获取cookie
    cart_cookie = request.COOKIES.get("cart_cookie", None)

    # 2. 判断是否有cookie,没有直接返回
    if cart_cookie is None:
        return response

    # 3. 解密cookie，判断解密后的字典是否为空，为空直接返回
    data = pickle.loads(base64.b64decode(cart_cookie))
    if data is None:
        return response

    # 4. 将cookie存储转为redis存储
    cart = {}
    cart_list = []  # 选中状态
    cart_list_no = []  # 未选中状态
    for sku_id, data_dict in data.items():
        cart[sku_id] = data_dict["count"]
        # 判断选中状态
        if data_dict["selected"]:
            cart_list.append(sku_id)
        else:
            cart_list_no.append(sku_id)

    # 写入redis
    conn = get_redis_connection("cart")
    conn.hmset("cart_{}".format(user.id), cart)

    if cart_list:
        conn.sadd("cart_selected_{}".format(user.id), *cart_list)

    if cart_list_no:
        conn.srem("cart_selected_{}".format(user.id), *cart_list_no)

    # 5. 删除cookie
    response.delete_cookie("cart_cookie")

    return response